package com.jl.security;

import java.security.GeneralSecurityException;

import com.jl.card.ErrorProcess;
import com.jl.card.JL;
import com.jl.security.mac.ALG_DES_MAC4_ISO9797_1_M2_ALG3;
import com.jl.security.mac.ALG_DES_MAC8_ISO9797_1_M2_ALG3;
import com.jl.security.mac.ALG_DES_MAC8_ISO9797_M2;
import com.jl.security.mac.IMac;

public class Mac {
	
	static{
		Crypto.init();
	}

	/** security provider name */
	private final static String providerName = "BC";

	/** default iv value */
	private static final byte[] defaultIV = new byte[] { 0, 0, 0, 0, 0, 0, 0,
			0, };

	public static byte[] sign(String name, byte[] key, byte[] data, byte[] iv) {
		try {
			byte[] biv = null;
			if (iv != null && iv.length != 0) {
				biv = iv;
			} else {
				biv = defaultIV;
			}
			IMac mac = getIMAC(name);
			if (mac == null) {
				throw new GeneralSecurityException(name + " not exist");
			}
			mac.initKey(key);
			mac.initIV(biv);
			return mac.doFinal(data);
		} catch (GeneralSecurityException e) {
			ErrorProcess.throwRuntimeException(e.getMessage());
			return null;
		}
	}

	public static boolean verify(byte[] exp, String name, byte[] key,
			byte[] data, byte[] iv) {
		byte[] biv = null;
		if (iv != null && iv.length != 0) {
			biv = iv;
		} else {
			biv = defaultIV;
		}
		byte[] res = sign(name, key, data, biv);
		if (res == null) {
			return false;
		}
		if (res.length != exp.length) {
			return false;
		}
		for (int i = 0; i < exp.length; i++) {
			if (exp[i] != res[i]) {
				return false;
			}
		}
		return true;
	}

	private static IMac getIMAC(String name) {
		if (name.equalsIgnoreCase("PBOC")
				|| name.equalsIgnoreCase(JL.MAC4_DES_ISO9797_1_M2_ALG3)) {
			return new ALG_DES_MAC4_ISO9797_1_M2_ALG3();
		} else if (name.equalsIgnoreCase(JL.MAC8_DES_ISO9797_M2)) {
			return new ALG_DES_MAC8_ISO9797_M2();
		} else if (name.equalsIgnoreCase(JL.MAC8_DES_ISO9797_1_M2_ALG3)) {
			return new ALG_DES_MAC8_ISO9797_1_M2_ALG3();
		}
		return null;
	}
}
